package com.lemurian.bankdata.lite.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringEscapeUtils;

import com.lemurian.bankdata.lite.logger.BankDataLogger;

public class BankDataCommons {

	public static final String BANKDATA_SYSTEM_PROPERTIES = Messages.getString("BankDataCommons.system.properties"); //$NON-NLS-1$
	public static final String BANKDATA_SQL_QUERY_PROPERTIES = Messages.getString("BankDataCommons.sqlQuery.properties"); //$NON-NLS-1$
	public static final String BANKDATA_ACTIVITY_LOG_PROPERTIES = Messages.getString("BankDataCommons.activityLog.properties"); //$NON-NLS-1$
	
	private static transient PropertiesConfiguration bankdataConfig = null;
    private static transient PropertiesConfiguration bankdataSQLConfig = null;
    private static transient PropertiesConfiguration bankdataActivityLogConfig = null;
	
    static final Object LOCK4 = new Object();
    static final Object LOCK5 = new Object();
    static final Object LOCK6 = new Object();
    static final Object LOCK7 = new Object();
    static BankDataLogger log = BankDataLogger.getLogger(BankDataCommons.class.getName());
    private static String characters[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    private static String numbers[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    
    public static PropertiesConfiguration createConfigFile(String file, boolean disableDelimiter) {
        try {
            PropertiesConfiguration config = new PropertiesConfiguration();
            config.setDelimiterParsingDisabled(disableDelimiter);
            File f = new File(file);
            config.load(file);
            config.setReloadingStrategy(new FileChangedReloadingStrategy());
            return config;
        } catch (Throwable th) {
            th.printStackTrace();
            return null;
        }

    }

    public static PropertiesConfiguration getBankDataConfig() {
        synchronized (LOCK4) {
            if (bankdataConfig == null) {
                bankdataConfig = createConfigFile(BANKDATA_SYSTEM_PROPERTIES, false);
            }
        }
        return bankdataConfig;
    }

    public static PropertiesConfiguration getBankDataSQLConfig() {
        synchronized (LOCK5) {
            if (bankdataSQLConfig == null) {
                bankdataSQLConfig = createConfigFile(BANKDATA_SQL_QUERY_PROPERTIES, true);
            }
        }
        return bankdataSQLConfig;
    }

    public static PropertiesConfiguration getBankDataActivityLogConfig() {
        synchronized (LOCK7) {
            if (bankdataActivityLogConfig == null) {
                bankdataActivityLogConfig = createConfigFile(BANKDATA_ACTIVITY_LOG_PROPERTIES, true);
            }
        }
        return bankdataActivityLogConfig;
    }

    public static String maskCard(String cardNo) {
        if (cardNo == null || cardNo.length() < 16) {
            return null;
        }
        return cardNo.replaceAll("([0-9]{6})(\\d{4,6})(?=)([0-9]{4})", "$1******$3");
    }

    public static String getCurrentDate(String format) {
        if (format.equals("")) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat day = new SimpleDateFormat(format);
        return day.format(new Date());
    }

    public static String createPassKey() {
        String array[] = numbers;
        String pswd = "";
        for (int i = 0; i < 6; i++) {
            double rnd = Math.random() * array.length;
            int rnd1 = (int) rnd;
            pswd += array[(rnd1)];
        }
        return pswd;
    }

    public static Date parseStringToDate(String date, SimpleDateFormat dateFormat) {
        Date dateParse = null;

        try {
            dateParse = dateFormat.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dateParse;
    }

    public static String parseDateToString(Date date, SimpleDateFormat dateFormat) {
        String dateParse = "";

        try {
            dateParse = dateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dateParse;
    }
    static private final String IPV4_REGEX = "(([0-1]?[0-9]{1,2}\\.)|(2[0-4][0-9]\\.)|(25[0-5]\\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))";
    static private Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);

    public static boolean isValidIPV4(final String s) {
        return IPV4_PATTERN.matcher(s).matches();
    }

    public static <T extends Enum> List<T> getList(Class<T> clazz) {
        return Arrays.asList(clazz.getEnumConstants());
    }

    public static String trimString(String string, int length, boolean soft) {
        if (string == null || string.trim().isEmpty()) {
            return string;
        }

        StringBuffer sb = new StringBuffer(string);
        int actualLength = length - 3;
        if (sb.length() > actualLength) {
            // -3 because we add 3 dots at the end. Returned string length has to be length including the dots.
            if (!soft) {
                return StringEscapeUtils.escapeHtml(sb.insert(actualLength, "...").substring(0, actualLength + 3));
            } else {
                int endIndex = sb.indexOf(" ", actualLength);
                return StringEscapeUtils.escapeHtml(sb.insert(endIndex, "...").substring(0, endIndex + 3));
            }
        }
        return string;
    }
}
